chrome.storage.sync.get("linkOpen", ({ linkOpen }) => {
    if (linkOpen) {
        if (window.isScriptLoaded) {
            console.log('Script already loaded');
        } else {
            window.isScriptLoaded = true;  // 设置标志变量
            console.log('Injecting script');

            console.log("插件开启")
            console.log(document.title)
            innerHtml("/html/ai.html",'ai-plugin')
            innerJs("/js/sweetalert2.all.min.js")
            setTimeout(function (){
                innerJs("/js/injected.js")
            },100)

        }
    }else {
        console.log("插件关闭")
    }
});


function innerJs(name){
    const  setScript = document.createElement("script");
    const head=document.head || document.getElementsByTagName('head')[0];
    setScript.src=chrome.runtime.getURL(name)
    setScript.type="text/javascript"
    head.appendChild(setScript);
}

function insertCss(name) {
    const link = document.createElement("link");
    const head = document.head || document.getElementsByTagName('head')[0];
    link.rel = "stylesheet";
    link.href = chrome.runtime.getURL(name);
    head.appendChild(link);
}

function innerHtml(name,tagName){
    fetch( chrome.runtime.getURL(name))
        .then(response => response.text())  // 解析为文本
        .then(text => {
            const n = document.createElement(tagName);
            n.id=tagName
            n.setAttribute("srcId",chrome.runtime.id)
            document.body.parentNode.insertBefore(n, document.body.nextSibling)
            const shadowRoot = n.attachShadow({mode: "open"})
            shadowRoot.innerHTML=text
        })
        .catch(error => {
            console.error("Failed to load file:", error);
        });
}

